package itheima05;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author xxx
 * @date 2020/12/27 20:15
 * @description
 */
public class Test {

    public static void main(String[] args) throws IOException {
         //服务器给浏览器响应.html文件前,必须下发送以下三行内容
         //netOs.write("HTTP/1.1 200 OK\r\n".getBytes());
        //netOs.write("Content-Type:text/html\r\n".getBytes());
        // netOs.write("\r\n".getBytes());

       //等待响应
        ServerSocket serverSocket=new ServerSocket(9999);
        //接受响应连接，返回个Socket对象
        while (true){
            Socket socket=serverSocket.accept();
             new Thread(new Runnable() {
                @Override
                public void run() {
                try {
                    //获取浏览器解析index的html文件，并向回传送要传输的图片文件地址
                    InputStream  inputStream=socket.getInputStream();
                    BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));

                    String line= bufferedReader.readLine();
                    System.out.println("-------------1");
                    System.out.println(line);
                    System.out.println("-------------2");
                    String path=line.split(" ")[1].substring(1);
                    //拆解得到真正的文件地址
                    System.out.println(path);

                    if (path.contains("favicon.ico")){
                       return;
                    }
                    //以字节方式读取获取图片
                    FileInputStream fileInputStream=new FileInputStream(path);
                    //将图片以字节方式传到浏览器，让浏览器自己解析回图片
                    OutputStream outputStream=socket.getOutputStream();

                    outputStream.write("HTTP/1.1 200 OK\r\n".getBytes());
                    outputStream.write("Content-Type:text/html\r\n".getBytes());
                    outputStream.write("\r\n".getBytes());

                    int b=0;
                    byte[] bytes=new byte[1024];
                    while ((b=fileInputStream.read(bytes))!=-1){
                        outputStream.write(bytes,0,b);
                    }

                    bufferedReader.close();
                    fileInputStream.close();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                }
            }).start();
        }




    }
}
